import { Modal as AntModal } from 'antd';
import React, { useEffect, useRef } from 'react';
import Draggable from 'react-draggable';
import { useConfig } from '../ConfigProvider';
import { useDraggable } from './hooks/useDraggable';
import { useResizable } from './hooks/useResizable';
import { useSwapButtons } from './hooks/useSwapButtons';
import type { XwdModalProps } from './interface';
import './styles/index.less';

const Modal: React.FC<XwdModalProps> = (props) => {
  const {
    antNative,
    draggable,
    resizable,
    autoHeight,
    minWidth = 520,
    minHeight = 200,
    maxWidth = window.innerWidth,
    maxHeight = window.innerHeight,
    swapButtons,
    onDragStart,
    className,
    style,
    title,
    ...restProps
  } = props;

  const { antNative: globalAntNative } = useConfig();
  const modalContentRef = useRef<HTMLDivElement>(null);

  // 如果使用原生组件，直接返回
  if (antNative || globalAntNative) {
    return <AntModal {...restProps}>{props.children}</AntModal>;
  }

  // 使用自定义 Hook
  const {
    draggleRef,
    disabled,
    bounds,
    handleDragStart,
    renderDraggableTitle,
  } = useDraggable({
    draggable,
    onDragStart,
    title,
  });

  const { modalRef, size, handleResizeStart } = useResizable({
    resizable,
    minWidth,
    minHeight,
    maxWidth,
    maxHeight,
  });

  const { footer } = useSwapButtons({
    swapButtons,
    onOk: restProps.onOk,
    onCancel: restProps.onCancel,
    okText: restProps.okText,
    cancelText: restProps.cancelText,
  });

  const handleAfterOpenChange = (open: boolean) => {
    if (open && modalRef.current) {
      const currentModal = modalRef.current.closest('.ant-modal');
      if (!currentModal) return;

      const modalBody = currentModal.querySelector('.ant-modal-body');
      if (modalBody) {
        const bodyElement = modalBody as HTMLElement;
        bodyElement.style.height = '100%';
        bodyElement.style.overflow = 'auto';

        if (autoHeight && !resizable) {
          const header = currentModal.querySelector('.ant-modal-header');
          const footer = currentModal.querySelector('.ant-modal-footer');
          const headerHeight = header ? header.getBoundingClientRect().height : 0;
          const footerHeight = footer ? footer.getBoundingClientRect().height : 0;
          const availableHeight = window.innerHeight * 0.8 - headerHeight - footerHeight;
          bodyElement.style.maxHeight = `${availableHeight}px`;
        }
      }
    }
  };

  const renderResizeHandles = () => {
    if (!resizable) return null;

    return (
      <>
        <div className="resize-handle right" onMouseDown={handleResizeStart} />
        <div className="resize-handle bottom" onMouseDown={handleResizeStart} />
        <div className="resize-handle corner" onMouseDown={handleResizeStart} />
      </>
    );
  };

  return (
    <div>
      <AntModal
        {...restProps}
        title={renderDraggableTitle()}
        footer={footer}
        className={className}
        wrapClassName={`${draggable ? 'xwd-modal-draggable' : ''} ${
          resizable ? 'xwd-modal-resizable' : ''
        }`}
        style={{
          ...style,
        }}
        width={resizable && size?.width > 0 ? size.width : undefined}
        afterOpenChange={handleAfterOpenChange}
        modalRender={(modal) => {
          const modalContent = (
            <div
              ref={modalRef}
              style={{
                position: 'relative',
              }}
            >
              {modal}
              {resizable && (
                <>
                  <div
                    className="resize-handle right"
                    onMouseDown={handleResizeStart}
                  />
                  <div
                    className="resize-handle bottom"
                    onMouseDown={handleResizeStart}
                  />
                  <div
                    className="resize-handle corner"
                    onMouseDown={handleResizeStart}
                  />
                </>
              )}
            </div>
          );

          if (!draggable) {
            return modalContent;
          }

          return (
            <Draggable
              disabled={disabled}
              bounds={bounds}
              nodeRef={draggleRef}
              onStart={handleDragStart}
            >
              <div ref={draggleRef}>{modalContent}</div>
            </Draggable>
          );
        }}
      >
        {props.children}
      </AntModal>
    </div>
  );
};

export default Modal;
